package net.lovesrc.support.service.generator.idcard;

import com.zhouzhou.fastjava.http.MyHttpRequest;
import com.zhouzhou.fastjava.http.Requests;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import java.util.HashSet;
import java.util.Set;

/**
 * 身份证生成web实现
 * @author gelic
 * Created in 10:10 2018/10/30
 * @since
 */
public class IDCardGeneratorServiceWebImpl implements IDCardGeneratorService {

    /**
     * 从网络获取身份证
     * @return
     */
    public Set<IDCard> getIDCardsFromWeb() {
        BasicCookieStore cookieStore = new BasicCookieStore();
        HttpClient httpClient = Requests.newHttpClient(cookieStore);
        String text = MyHttpRequest.get(httpClient, "http://sfz.ckd.cc/idcard.php")
                .printResText(false)
                .execute()
                .asText();

        Document document = Jsoup.parse(text);
        Elements tbody = document.getElementsByTag("tbody");
        Element element = tbody.get(0);
        Elements children = element.children();

        Set<IDCard> idCards = new HashSet<>();

        for (Element child : children) {
            Elements tds = child.getElementsByTag("td");
            if (tds.size() == 3) {
                Element nameEle = tds.get(0);
                Element genderEle = tds.get(1);
                Element addrEle = tds.get(2);
                String[] nameSplit = nameEle.text().split(" ");
                if (nameSplit.length == 2) {
                    idCards.add(new IDCard(nameSplit[0].trim(), nameSplit[1].trim(), genderEle.text().trim(), addrEle.text().trim()));
                }
            }
        }
        return idCards;
    }

    @Override
    public IDCard generate() {
        return generate(1).stream().findFirst().get();
    }

    @Override
    public Set<IDCard> generate(int size) {
        Set<IDCard> idCards = new HashSet<>();
        for (; idCards.size() < size; ) {
            getIDCardsFromWeb().stream().forEach(idCard -> {
                if(idCards.size() < size) {
                    idCards.add(idCard);
                }
            });
        }
        return idCards;
    }
}
